package net.lzzy.practices.web;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import net.lzzy.practices.constants.ApiConstant;
import net.lzzy.practices.constants.Messages;
import net.lzzy.practices.entities.User;
import net.lzzy.practices.services.UserService;
import net.lzzy.practices.services.UserServiceImpl;
import net.lzzy.practices.utils.FileUtil;
import net.lzzy.practices.utils.JwtUtil;
import net.lzzy.practices.utils.StringUtil;
import net.lzzy.practices.web.models.ApiResult;
import net.lzzy.practices.web.models.LoginInfo;
import net.lzzy.practices.web.models.RegisterInfo;
import net.lzzy.practices.web.models.VmUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author m
 */
//@CrossOrigin("http://")
@CrossOrigin //允许不同域名访问
@Api(tags = "用户认证")
@RestController
@RequestMapping(ApiConstant.ROUTE_AUTH_ROOT)
//@Component
public class AuthApiController {

    private  final UserServiceImpl service;

    @Autowired
    public AuthApiController(UserServiceImpl service) {
        this.service = service;
    }

    @ApiOperation( "登录")
    @ApiImplicitParam(name = "info",value = "用登入信息",
            dataType ="LoginInfo",
            dataTypeClass = LoginInfo.class,
            paramType = "body",required = true)
    @PostMapping(value = ApiConstant.ROUTE_AUTH_LOGIN,produces = ApiConstant.API_PRODUCES)
    public ApiResult login(@RequestBody LoginInfo info){
        String userName= info.getUsername();

        String password= info.getPassword();
        System.out.println(password);
        String salt=service.getSalt(userName);
        System.out.println(salt);
//        195b80519e6c15429c4690f2dd022384
        //9b70d6dbfb1457d05e4e2c2fbb42d7db 6978915ee7dbc5aff1bc34b59e8c0fc5
        //07bd30a0021280e8be90d60c60ad6919
        System.out.println(StringUtil.md5Encode(userName,salt));
        //查询账户密码
        User user= service.check(userName,StringUtil.md5Encode(password,salt));
//        System.out.println( service.check(userName,StringUtil.md5Encode(password,salt)));

        //判断账户是否存在
        if(user==null){
            return  new ApiResult(false, Messages.WRONG_PASSWORD.toString(), null);

        }
        //判断是否有权限登入
        if (user.getType()<0) {
            return  new ApiResult(false,Messages.NO_PERISSION.toString(),null);
        }

        VmUser vmUser = VmUser.apiLogin(user);
        return  new ApiResult(true, Messages.SUCCESC.toString(),vmUser);



    }
    //检查用户是否存在
    @ApiOperation("检查用户是否存在")
    @GetMapping(ApiConstant.ROUTE_AUTH_EXISTS)
    public  ApiResult isUserExists(@PathVariable String user){
        boolean exists= service.isUserNameOccupied(user);
        return  new ApiResult(true,exists ? "用户已存在": "",exists);

    }

    @ApiOperation("注册新用户")
    @PostMapping(value = ApiConstant.ROUTE_AUTH_REGISTER,produces = ApiConstant.API_PRODUCES)
    public  ApiResult register(@RequestBody RegisterInfo info){
        String nick= info.getNick();
        String user= info.getUser();
        String phone= info.getPhone();
        String email= info.getEmail();
        String pwd= info.getPwd();
        String avatar= info.getAvatar();
        boolean teacher= info.isTeacher();
        String salt= UUID.randomUUID().toString();

        if (StringUtil.isEmpty(nick)){
            nick=user;
        }
        //判断格式是否为空
        if(StringUtil.isEmpty(user)||
            StringUtil.isEmpty(avatar)||
                StringUtil.isEmpty(phone)||
                StringUtil.isEmpty(email)||
                StringUtil.isEmpty(pwd)
        ){
            return  new ApiResult(false,Messages.MISS_ARGS.toString(),null);

        }
        //判断格式
        if(!StringUtil.validMail(email)|| StringUtil.validPhone(phone)){
            return  new ApiResult(false,Messages.INVALID_FORMAT.toString(),null);
        }
        //检查用户是否存在
        if(service.isUserNameOccupied(user)){
            return  new ApiResult(false,"用户已存在",null);
        }

        User usr= new User();
        usr.setUserName(user);
        usr.setAvatar(avatar);
        usr.setEmail(email);
        usr.setPhone(phone);
        usr.setNickName(nick);
        usr.setSalt(String.valueOf(User.TYPE_STUDENT));
//        PasswordEncoder passwordEncoder1 = PasswordEncoderFactories.createDelegatingPasswordEncoder();
//        usr.setSalt("2");
        usr.setPassword(StringUtil.md5Encode(pwd,salt));
        System.out.println(usr.getPassword());
        VmUser vmUser = VmUser.apiLogin(service.register(usr));



    return  new  ApiResult(true,Messages.SUCCESC.toString(),vmUser);
    }
    @Value("${user.pic}")
    private  String path;
    @PostMapping(ApiConstant.ROUTE_AUTH_UPLOAD)
    public  ApiResult upload(@RequestParam("avatar") MultipartFile file){
        JSONObject result= FileUtil.uploadWithRandomName(file,path);
        return  new ApiResult(
                result.getBoolean(FileUtil.UPLOAD_PARAM_STATUS),
                result.getString(FileUtil.UPLOAD_PARAM_MESSAGE),
                result.getString(FileUtil.UPLOAD_PARAM_URL)
                );

    }
}
